<?php


namespace Melon;


use EventBuffer;
use EventHttpRequest;

class Response
{
    /**
     * @var EventHttpRequest
     */
    protected EventHttpRequest $request;

    /**
     * @var string
     */
    protected string $data = '';

    /**
     * @var array
     */
    protected array $headers = [];

    protected int $code = 200;

    /**
     * @param EventHttpRequest $request
     */
    public function __construct(EventHttpRequest $request)
    {
        $this->request = $request;

        $this->headers = [
            "Content-Type" => "text/html; charset=UTF-8",
            "Server" => "Melon"
        ];
    }

    /**
     * @param string $data
     * @return $this
     */
    public function setContent(string $data): self
    {
        $this->data = $data;
        return $this;
    }

    public function setCode(int $code): self
    {
        $this->code = $code;
        return $this;
    }

    /**
     * add header
     * @param string $key
     * @param string $value
     * @param bool $replace
     * @return $this
     */
    public function header(string $key, string $value, bool $replace = false): Response
    {
        $key = trim($key);
        $value = trim($value);

        if (empty($key) || empty($value)) {
            return $this;
        }

        if (isset($this->headers[$key])) {
            if ($replace) {
                $this->headers[$key] = $value;
            }
        } else {
            $this->headers[$key] = $value;
        }
        return $this;
    }

    public function send()
    {
        foreach ($this->headers as $key => $item) {
            $this->request->addHeader($key, $item, EventHttpRequest::OUTPUT_HEADER);
        }
        $this->request->addHeader("Content-Type", "text/html; charset=UTF-8", EventHttpRequest::OUTPUT_HEADER);

        $buffer = new EventBuffer();
        $buffer->add($this->data);

        $this->request->sendReply($this->code, $this->code == 200 ? 'OK' : "Internal Server Error", $buffer);
    }
}
